/*
 * Connection.cpp
 *
 *  Created on: 04/06/2011
 *      Author: dela
 */

#include "ServerConnection.h"

#include <string>
#include <iostream>
#include "common/User.h"
#include "Server.h"

using namespace std;

/**
 *
 */
bool ServerConnection::doLogin(char type) {
	string userName = "";
	string password = "";
	char *data;
	int dataSize = 0;
	// Nombre:
	dataSize = socket.receiveData(&data);
	userName.append(data, dataSize);
	delete[] data;
	// Contraseña:
	dataSize = socket.receiveData(&data);
	password.append(data, dataSize);
	delete[] data;

	//Retorno valor:
	bool returnValue = false;

	User user;
	if ( Server::getInstance()->getUser(userName, user) ) {
		if ( password == user.getPassword() && (type == 'S' || type == user.getType()) ) {
			returnValue = true;
			this->userName = userName;
		}
	}
	socket.sendData(1, (char*) &returnValue);
	return returnValue;
}


/**
 *
 */
void ServerConnection::connectionShutdown() {
	setWorking(false);
	socket.shutdownSocket();
}

/**
 *
 */
bool ServerConnection::returnCourses() {
	// Envio cantidad:
	int amount = Server::getInstance()->getCourses().size();
	socket.sendData(4, (char*) &amount);

	// Envio:
	int size;
	std::map<unsigned int, Course*>::iterator it;
	std::map<unsigned int, Course*> &courses = Server::getInstance()->getCourses();
	for ( it=courses.begin() ; it != courses.end(); it++ ) {
	    char *buff = (*it).second->toBuffer( &size );
		socket.sendData(size, buff);
		delete[] buff;
	}

	return true;
}


/**
 *
 */
bool ServerConnection::returnClasses() {
	// Envio cantidad:
	int amount = Server::getInstance()->getClasses().size();
	socket.sendData(4, (char*) &amount);

	// Envio:
	int size;
	std::map<unsigned int, Class*>::iterator it;
	std::map<unsigned int, Class*> &classes = Server::getInstance()->getClasses();
	for ( it=classes.begin() ; it != classes.end(); it++ ) {
	    char *buff = (*it).second->toBuffer( &size );
		socket.sendData(size, buff);
		delete[] buff;
	}

	return true;
}
